<template>
  <div class="white-list">
    <div class="header">
      <div class="title">白名单管理</div>
      <div class="tips">
        <div class="tips-box">
          <i class="iconfont icon-tishitubiao"></i>
          <span>研发阶段，项目人员使用白名单账号进行调试</span>
        </div>
      </div>
    </div>

    <div>
      <el-form :inline="true" class="search-form">
        <el-col :span="10">
          <el-form-item>
            <el-input v-model="nameOrPhone" placeholder="输入姓名/手机号码" clearable @keyup.enter.native="queryList('search')">
              <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('search')"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-button type="primary" class="button-container" size="14" @click="handleAdd">新增</el-button>
        </el-col>
      </el-form>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }">
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.username || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="角色">
        <template slot-scope="scope">
          {{ scope.row.roleName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码">
        <template slot-scope="scope">
          {{ scope.row.phone || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="95">
        <template #header>
          <el-popover ref="statusPopover" placement="bottom" width="127" trigger="click" popper-class="custom-popover">
            <div slot="reference">
              <span class="search-title">状态</span>
              <i class="iconfont icon-biaogeshaixuan"></i>
            </div>
            <el-checkbox-group v-model="selectValue" class="status-group">
              <el-checkbox
                v-for="item in selectOptions"
                :key="item.value"
                :value="item.value"
                :label="item.value"
                class="status-checkbox">
                <div>{{ item.label }}</div>
              </el-checkbox>
            </el-checkbox-group>
            <div class="status-btn-box">
              <el-button size="mini" type="primary" class="btn" @click="filterStatus">确定</el-button>
            </div>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <span class="identifying" :class="scope.row.lockFlag === '9' ? 'disable' : ''"></span>
          <span v-if="scope.row.lockFlag === '0'">
            正常
          </span>
          <span v-else>
            禁用
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="operate" @click="handleStatus(scope.row)">{{ scope.row.lockFlag === '0' ? '禁用' :
            '启用'
          }}</el-button>
          <el-button
            type="text"
            size="operate"
            :disabled="scope.row.lockFlag === '0'"
            @click="handleDelete(scope.row.whiteUserId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>

    <el-dialog
      :title="status === 'add' ? '新建白名单' : '编辑白名单'"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        class="define-form"
        :model="addFormData"
        :rules="rules"
        label-width="80px"
        label-position="left">
        <el-form-item label="姓名" prop="username">
          <template #label>
            <span>姓名</span>&nbsp;
            <el-tooltip content="支持中英文,长度2-32" placement="top">
              <i class="iconfont icon-wenhao"></i>
            </el-tooltip>
          </template>
          <el-input v-model="addFormData.username" placeholder="请输入姓名" maxlength="32" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="addFormData.phone" placeholder="请输入手机号码" clearable :disabled="status === 'edit'"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleCode">
          <el-select v-model="addFormData.roleCode" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleData"
              v-if="item.showFlag"
              :key="item.roleCode"
              :label="item.roleName"
              :value="item.roleCode"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { whiteUserList, addWhiteUser, modifyWhiteUser, deleteWhiteUser, modifyLockFlag } from '@/api/app/white-list'
import { list } from '@/api/app/approle'
export default {
  name: "WhiteList",
  data() {
    return {
      nameOrPhone: "", // 产品id或名称
      tableData: [], // 列表数据
      roleData: [], // 角色数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      selectValue: [], // 列表开发状态选中的数据
      selectOptions: [ // 列表开发状态
        {
          value: 0,
          label: '正常'
        },
        {
          value: 9,
          label: '禁用'
        }
      ],
      loading: true,
      dialogVisible: false,
      addFormData: {
        username: '',
        phone: '',
        roleCode: '',
        whiteUserId: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 32, message: '请输入规范的姓名', trigger: 'blur' },
          { validator: this.validateName, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {},
          { validator: this.validatePhone, trigger: 'blur' }
        ],
        roleCode: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      status: ''
    }
  },
  created() {
    this.queryList()
    this.queryRoleList()
  },
  methods: {
    // 姓名校验
    validateName(rule, value, callback) {
      const flag = new RegExp(/^[\u4E00-\u9FA5A-Za-z]+$/).test(value)
      if (!flag) {
        callback(new Error('请输入规范的姓名'))
      } else {
        callback()
      }
    },
    // 手机号校验
    validatePhone(rule, value, callback) {
      const flag = new RegExp(/^1[34578]\d{9}$/).test(value)
      if (!flag) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    },
    /**
     * 查询白名单列表
     * current 当前页码
     * size 每页条数
     */
    queryList(condition) {
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        lockFlagList: this.selectValue,
        phoneOrUsername: this.nameOrPhone
      }
      whiteUserList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 查询角色列表
    queryRoleList() {
      list().then(res => {
        this.roleData = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 新增
    handleAdd() {
      this.dialogVisible = true
      this.status = 'add'
    },
    // 编辑
    handleEdit(row) {
      this.dialogVisible = true
      this.status = 'edit'
      this.addFormData.username = row.username
      this.addFormData.phone = row.phone
      this.addFormData.roleCode = row.roleCode
      this.addFormData.whiteUserId = row.whiteUserId
    },
    // 启用或禁用状态
    handleStatus(row) {
      const params = {
        whiteUserId: row.whiteUserId,
        lockFlag: row.lockFlag === '0' ? '9' : '0'
      }
      modifyLockFlag(params).then(res => {
        this.$message.success('修改成功')
        this.queryList()
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 删除账号
    handleDelete(whiteUserId) {
      this.$confirm('产品删除后不可恢复，请谨慎操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWhiteUser(whiteUserId).then(res => {
          if (res.data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.queryList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {})
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    },
    // 列表开发状态查询
    filterStatus() {
      this.queryList()
      this.$refs.statusPopover.doClose()
    },
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData
          }
          if (this.status === 'add') {
            addWhiteUser(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          } else {
            modifyWhiteUser(params).then(res => {
              this.queryList()
            }).catch(err => {
              this.$message.error(err.message)
            })
          }
          this.dialogVisible = false
          this.$refs['form'].resetFields()
        } else {
          return false
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.white-list {
  height: 100%;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 17px;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #252525;
    }

    .tips {
      display: inline-block;
      height: 34px;
      background: rgba(61, 113, 239, 0.1);
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #759AF2;
      font-weight: 400;
      color: #000000;
      font-size: 12px;
      line-height: 34px;
      float: right;
      text-align: center;
      padding: 0 12px;
      margin-left: 20px;

      .tips-box {
        display: flex;
        align-items: center;
      }
    }
  }

  .search-icon {
    cursor: pointer;
  }

  .search-form .tips {
    display: inline-block;
    height: 34px;
    background: rgba(61, 113, 239, 0.1);
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #759AF2;
    font-weight: 400;
    color: #000000;
    font-size: 12px;
    line-height: 34px;
    float: right;
    text-align: center;
    padding: 0 12px;

    .tips-box {
      display: flex;
      align-items: center;
    }
  }

  .button-container {
    float: right;
    margin-left: 32px;
  }
}

.iconfont {
  margin-left: 2px;
  margin-right: 2px;
  margin-top: 2px;
  cursor: pointer;
}

.status-group {
  padding: 0 12px;

  .status-checkbox {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}

.status-btn-box {
  text-align: center;
  border-top: 1px solid #E5E6E9;
  margin-top: 10px;

  .btn {
    margin-top: 10px;
  }
}

.identifying {
  width: 6px;
  height: 6px;
  display: inline-block;
  background: #1CBE49;
  border-radius: 50%;
  margin-right: 2px;
  margin-bottom: 1px;
}

.disable {
  background: #AEB0B9;
}

::v-deep .el-table__fixed-right-patch {
  background: #F5F6F7;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-group__append {
  background: transparent;
}

::v-deep .white-list-dialog .el-dialog__body {
  padding: 20px 80px !important;
}
</style>
<style>
.custom-popover {
  min-width: 127px !important;
  padding: 12px 0;
}
</style>
